package main

import (
	"bufio"
	"embed"
	"fmt"
	"go-admin/config"
	"go-admin/daos"
	_ "go-admin/daos"
	"go-admin/models"
	"go-admin/service"
	"go-admin/utils"
	"net"
	"os"
	"regexp"
	"strings"
	"time"
)

//go:embed config
var AssertFile embed.FS

func tips() {
	fmt.Println("========================================")
	fmt.Println()
	fmt.Printf("马岭水库水质监测接收程序启动成功！技术支撑QQ:397633183 请勿关闭程序!%s\n", time.Now().Format("2006-01-02 15:04:05"))
	fmt.Println()
	fmt.Println("========================================")
}

func main() {
	fmt.Println(time.Now())
	var cstZone = time.FixedZone("CST", 8*3600) // 东八
	time.Local = cstZone

	tips()
	config.OpenDB(AssertFile)
	daos.OpenConnect()
	startTcp()
}

func startTcp() {
	listen, err := net.Listen("tcp", "0.0.0.0:8081")
	if err != nil {
		fmt.Println("listen failed, err:", err)
		return
	}
	for {
		conn, err := listen.Accept()
		writeLog("有设备连接")
		if err != nil {
			fmt.Println("accept failed, err:", err)
			continue
		}
		go HandleTcpProcess(conn)
	}
}

func writeLog(msg string) {
	logFile, err := os.OpenFile("./log.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		fmt.Println("open log file failed, err:", err)
		return
	}
	logFile.WriteString(msg)
	logFile.WriteString("\n")
}

func HandleTcpProcess(conn net.Conn) {
	defer conn.Close()

	for {
		reader := bufio.NewReader(conn)
		var buf [1024]byte
		n, err := reader.Read(buf[:]) // 读取数据
		if err != nil {
			fmt.Println("read from client failed, err:", err)
			break
		}
		fmt.Printf("========================================\n")
		fmt.Printf("收到数据1:%v\n", string(buf[:n]))
		fmt.Printf("========================================\n")
		writeLog(string(buf[:n]))

		data := string(buf[:n])

		startIndex := strings.Index(data, "##")

		if startIndex == -1 {
			fmt.Println("Invalid HJ212 frame")
			conn.Write([]byte("success"))
			continue
		}

		//打印解析结果
		dataTime := ""
		deviceId := ""

		// 提取数据部分
		payload := data[startIndex+6:]
		for _, pay := range strings.Split(payload, ";") {
			parts := strings.SplitN(pay, "=", 2)
			if len(parts) == 2 {
				dataName := parts[0]
				dataValue := parts[1]
				if strings.EqualFold(dataName, "MN") {
					deviceId = dataValue
					continue
				}
			}
		}

		re := regexp.MustCompile(`&&([^&]*)&*`)
		result := re.FindStringSubmatch(payload)
		// 解析数据字段
		fields := strings.Split(result[1], ";")

		dataList := []models.Quality{}

		deviceData := map[string]string{}
		for _, field := range fields {

			if strings.Index(field, "DataTime") > -1 {
				timeArray := strings.Split(field, "=")
				dataTime = utils.FormatTime(timeArray[1])
			} else {
				itemData := strings.Split(field, ",")
				for _, datum := range itemData {
					dataArray := strings.Split(datum, "=")
					dataName := dataArray[0]
					dataValue := dataArray[1]
					//if strings.HasSuffix(dataName, "-Rtd") {
					if strings.HasSuffix(dataName, "-Avg") {
						dataName = strings.Replace(dataName, "-Avg", "", 1)
						deviceData[dataName] = dataValue
						continue
					}
				}
			}
		}

		for name, value := range deviceData {
			qualityModel := models.Quality{}
			qualityModel.CreateTime = time.Now().Format("2006-01-02 15:04:05")
			qualityModel.DeviceId = deviceId
			qualityModel.ProId = "105"
			tm, tmErr := time.Parse("2006-01-02 15:04:05", dataTime)
			if tmErr != nil {
				continue
			}
			qualityModel.DataTime = tm
			qualityModel.DataName = name
			qualityModel.DataValue = value
			dataList = append(dataList, qualityModel)
		}
		if len(dataList) == 0 {
			continue
		}
		qualityService := service.QualityService{}
		saveErr := qualityService.InsetBatch(&dataList)
		if saveErr != nil {
			fmt.Printf("数据写入失败：%s", saveErr.Error())
			continue
		}

		conn.Write([]byte("success")) // 发送数据
	}
}
